<?php

// +----------------------------------------------------------------------
// | Wechat Plugin for ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2023 Anyon <zoujingli@qq.com>
// +----------------------------------------------------------------------
// | 官方网站: https://thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// | 免责声明 ( https://thinkadmin.top/disclaimer )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/think-plugs-wechat
// | github 代码仓库：https://github.com/zoujingli/think-plugs-wechat
// +----------------------------------------------------------------------

namespace app\data\service;

use think\admin\Exception;
use think\admin\extend\JsonRpcClient;
use think\admin\Library;
use think\admin\storage\LocalStorage;
use think\exception\HttpResponseException;

use AlibabaCloud\SDK\Iot\V20180120\Iot;
use AlibabaCloud\Tea\Tea;
use AlibabaCloud\Tea\Utils\Utils;
use AlibabaCloud\Tea\Console\Console;
use AlibabaCloud\Tea\Exception\TeaError;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Iot\V20180120\Models\RegisterDeviceRequest;
use AlibabaCloud\SDK\Iot\V20180120\Models\DeleteDeviceRequest;
use AlibabaCloud\SDK\Iot\V20180120\Models\GenerateOTAUploadURLRequest;
use AlibabaCloud\SDK\Iot\V20180120\Models\QueryDeviceRequest;
use AlibabaCloud\SDK\Iot\V20180120\Models\BatchUpdateDeviceNicknameRequest\deviceNicknameInfo;
use AlibabaCloud\SDK\Iot\V20180120\Models\BatchUpdateDeviceNicknameRequest;
use app\data\service\IotThingService;
use app\data\model\DataStatisticsLog;
use app\data\model\DataCatLog;
class DeviceService
{
    private $client;
    public function __construct( )
    {
        $config = new Config([]);
        $config->accessKeyId = config('iot.accessKeyId');// 您的AccessKey ID。
        $config->accessKeySecret = config('iot.accessKeySecret');// 您的AccessKey Secret。
        $config->regionId = config('iot.regionId');// 您的可用区ID。
        $this->client = new Iot($config);
    }
    //修改设备
    public function BatchUpdateDeviceNickname($data){
        try {
            $deviceNicknameInfo0 = new deviceNicknameInfo($data);
            $request = new BatchUpdateDeviceNicknameRequest(["deviceNicknameInfo" => [$deviceNicknameInfo0],  "iotInstanceId" =>config('iot.IotInstanceId')]);
            $response =  $this->client->BatchUpdateDeviceNickname($request);
            $res['err_code']=0;
            $res['data'] = $response;
        } catch (TeaUnableRetryError $e) {
            $res['err_code']=1;
            $res['data'] = $e->getMessage();
        }
        return $res;
    }
    //添加设备
    public function registerDevice($data){
        try {
            $request = new RegisterDeviceRequest($data);
            $response =  $this->client->RegisterDevice($request);
            $res['err_code']=0;
            $res['data'] = $response;
        } catch (TeaUnableRetryError $e) {
            $res['err_code']=1;
            $res['data'] = $e->getMessage();
        }
        return $res;
    }
    //删除设备
    public function delDevice($data){
        try {
            $request = new DeleteDeviceRequest($data);
            $response =  $this->client->DeleteDevice($request);
            $res['err_code']=0;
            $res['data'] = $response;
        } catch (TeaUnableRetryError $e) {
            $res['err_code']=1;
            $res['data'] = $e->getMessage();
        }
        return $res;
    }
    //生成升级文件存储的OSS地址
    public function GenerateOTAUploadURL($data){
        try {
            $request = new GenerateOTAUploadURLRequest($data);
            $response =  $this->client->GenerateOTAUploadURL($request);
            $res['err_code']=0;
            $res['data'] = $response;
        } catch (TeaUnableRetryError $e) {
            $res['err_code']=1;
            $res['data'] = $e->getMessage();
        }
        return $res;
    }
    //批量查询设备
    public function QueryDevice($next=''){
        try {
            $data['productKey'] = config('iot.ProductKey');
            $data['iotInstanceId'] = config('iot.IotInstanceId');
            if($next!=''){
                $data['NextToken'] = $next;
            }
            $request = new QueryDeviceRequest($data);
            $response =  $this->client->QueryDevice($request);

            $res['err_code']=0;
            $res['data'] = $response;
        } catch (TeaUnableRetryError $e) {
            $res['err_code']=1;
            $res['data'] = $e->getMessage();
        }
        return $res;
    }
    //获取设备属性
    public function getDevicePro($iotId){
        $class = new IotThingService();
        $data=[
            'iotId'=>$iotId,//设备IOTid
            "iotInstanceId" =>  config('iot.IotInstanceId')
        ];
        $res = $class->getProp($data);
        if($res['err_code'] == 0){
            $response = $res['data'];
            if($response->body->code !=''){
                echo $response->body->code;
            }else{
                $json = json_encode($response->body->data->list->propertyStatusInfo);
                $arr = json_decode($json,true);//属性列表arr
                $res =[];
                foreach($arr as $key =>$v){
                    $res[$v['identifier']]=json_decode($v['value']);
                }
//                $index_array=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,18];
////                if (in_array($res['Prform_State'],$index_array)){
////                    $redis = redis();
////                    $redis->select(1);
////                    $redis->set($iotId, $res['Prform_State']);
////                }
                return $res;
            }
        }else{
            return [];
            // return $this->error($res['data']);
        }
    }
    //获取清理次数
    public function CleanTimes($iotId){
        $today_times = DataStatisticsLog::mk()
            ->where(['iot_id'=>$iotId,'type'=>'Times_Clean_Day'])->whereDay('create_at')->order('create_at desc')
            ->value('counts');
        $total_times = DataStatisticsLog::mk()
            ->where(['iot_id'=>$iotId,'type'=>'Times_Clean'])->order('create_at desc')
            ->value('counts');
        return ['today'=>$today_times?$today_times:0,'total'=>$total_times?$total_times:0];
    }
    //获取如厕次数
    public function toiletTimes($id){
        $res['today_times'] = DataCatLog::mk()->where(['iot_id'=>$id])->where('cat_id','>',0)->whereDay('in_time')->count();
        $res['yesterday_times'] = DataCatLog::mk()->where(['iot_id'=>$id])->where('cat_id','>',0)->whereDay('in_time', 'yesterday')->count();
        $compare = $res['today_times'] - $res['yesterday_times'];
        $res['compare'] = $compare;
        if($compare == 0){
            $res['vary'] = 0 ;
        }else if($compare > 0){
            $res['vary'] = 1 ;
        }else{
            $res['vary'] = 2 ;
        }
        //平均时长duration
        $today_avg = DataCatLog::mk()->where(['iot_id'=>$id])->where('cat_id','>',0)->whereDay('in_time')->avg('duration');
        $yesterday_avg = DataCatLog::mk()->where(['iot_id'=>$id])->where('cat_id','>',0)->whereDay('in_time', 'yesterday')->avg('duration');
        $res['today_avg'] = $today_avg;
        $res['yesterday_avg'] =$yesterday_avg;
        $compare_avg = round(($res['today_avg'] - $res['yesterday_avg']));
        $res['compare_avg'] = $compare_avg;
        if($compare_avg == 0){
            $res['vary_avg'] = 0 ;
        }else if($compare_avg > 0){
            $res['vary_avg'] = 1 ;
        }else{
            $res['vary_avg'] = 2 ;
        }
        return $res;
    }
}
